<template>
  <view style="width: 100%; height: var(--status-bar-height)" />
  <view class="flexSpaceBetween">
    <view class="flexSpaceBetween">
      <wd-button type="icon" icon="arrow-left" @click="weekCalendar(-1)"></wd-button>
      <view>{{ datePlan }}</view>
    </view>
    <wd-button v-if="minus < 0" type="icon" icon="arrow-right" @click="weekCalendar(1)"></wd-button>
  </view>
  <DateProgress ref="dateProgress" @handleDatePlanConfirm="handleDatePlanConfirm" />
  <view style="margin-top: 20px; text-align: center">
    <swiper :interval="10000" :autoplay="true" style="height: 300rpx" indicator-dots>
      <swiper-item>
        <view class="scroll-view-item_H">
          <wd-card>
            <view style="height:270rpx;">
              <view style="padding: 20px 0 0 0">
                <wd-button type="success" @click="planSelect.handleShow(energyPlan)">
                  &nbsp;&nbsp;能量限额：{{ energyPlan }}Kcal&nbsp;&nbsp;
                  <wd-icon name="edit-outline"></wd-icon>
                  &nbsp;&nbsp;
                </wd-button>
              </view>
              <wd-loading v-if="indexLoading"></wd-loading>
              <view
                v-else
                style="
                padding: 10px 0 15px 0;
                display: flex;
                justify-content: space-around;
                align-items: center;
              "
              >
                <view>
                  <view
                    class="sportTitle"
                    :style="energy < energyPlan ? { color: '#82d44f' } : { color: '#ee6666' }"
                  >
                    {{ energy }}Kcal
                  </view>
                  <view class="sportContent">能量摄入</view>
                </view>
                <view>
                  <view class="sportTitle">
                    {{ energyPlan - energy > 0 ? (energyPlan - energy).toFixed(1) : 0 }}Kcal
                  </view>
                  <view class="sportContent">还可以吃</view>
                </view>
              </view>
            </view>
          </wd-card>
        </view>
      </swiper-item>
      <swiper-item>
        <view class="scroll-view-item_H">
          <wd-card>
            <view style="height:270rpx;" @click="toTips">
              <wd-loading v-if="indexLoading"></wd-loading>
              <view v-else style="padding: 10px">
                <view class="foodCard">
                  <view class="carbon">碳水（{{ carbo.quantity }}克）</view>
                  <view class="process">
                    <wd-progress :percentage="carbo.percentage" color="#0079FE"></wd-progress>
                  </view>
                </view>
                <view class="foodCard">
                  <view class="protein">蛋白质（{{ protein.quantity }}克）</view>
                  <view class="process">
                    <wd-progress :percentage="protein.percentage" color="#33C759"></wd-progress>
                  </view>
                </view>
                <view class="foodCard">
                  <view class="fat">脂肪（{{ fat.quantity }}克）</view>
                  <view class="process">
                    <wd-progress :percentage="fat.percentage" color="#FE9400"></wd-progress>
                  </view>
                </view>
                <wd-divider></wd-divider>
                <view>营养均衡和热量控制一样重要哦~</view>
              </view>
            </view>
          </wd-card>
        </view>
      </swiper-item>
      <swiper-item>
        <view class="scroll-view-item_H">
          <wd-card>
            <view style="height:270rpx;">
              <wd-loading v-if="indexLoading"></wd-loading>
              <view v-else style="padding: 10px">
                <view class="foodCard">
                  <view class="foodCard">
                    <view style="font-size: 30px;color: #8a85ff;">{{ weather.temp+"℃" }}</view>
                    <view style="font-size: 20px;color: #8a85ff;"><i :class="`qi-${weather.icon}`"></i></view>
                  </view>
                  <view style="text-align: right">
                    <view style="font-size: 16px">{{ city.name }}</view>
                    <view style="color: #8a85ff;">{{ day.tempMax + "/" + day.tempMin + "℃" }}</view>
                    <view>{{ weather.text + " 空气" + aqiLevel }}</view>
                  </view>
                </view>
                <view class="foodCard">
                  <view v-for="(item, index) in hour" :key="index">
                    <view>{{ moment(item.fxTime).format("HH:mm") }}</view>
                    <view><i :class="`qi-${weather.icon}`"></i></view>
                    <view style="font-size: 10px;color: #8a85ff;">{{ item.temp + "℃"}}</view>
                  </view>
                </view>
              </view>
            </view>
          </wd-card>
        </view>
      </swiper-item>
    </swiper>
  </view>
  <wd-status-tip
    v-if="dietPlan == null || dietPlan.length === 0"
    type="search"
    tip="当前搜索无结果"
  />
  <view v-else>
    <view class="foodPlanTitle">饮食</view>
    <view class="planContent">
      <wd-card v-for="(item, index) in dietPlan" :key="index">
        <view
          class="flexSpaceBetween"
          @click="detailPopup.handleDetailShow(null, item)"
          @longpress="handlePlanDel(item.id, 'food')"
        >
          <view>
            <view style="font-size: 13px; margin: 5px 0 5px 0">
              {{ item.foodName }}
            </view>
            <view style="font-size: 11px; margin: 5px 0 5px 0">{{ item.quantity }}克</view>
          </view>
          <view style="font-weight: bold; color: #82d44f">+{{ item.energy }}千卡</view>
        </view>
      </wd-card>
    </view>
  </view>
  <wd-popup
    v-model="showPanel"
    :modal="false"
    position="bottom"
    style="max-height: 85vh"
    @close="showPanel = false"
  >
    <view style="max-height: 70vh; height: 70vh; overflow: auto">
      <wd-row custom-class="detailHead">
        <wd-col :span="6">
          <wd-radio-group v-model="searchType" shape="button" @change="foodList = []">
            <wd-radio :value="'饮食'">饮食</wd-radio>
          </wd-radio-group>
        </wd-col>
        <wd-col :span="18">
          <wd-search
            v-model="searchFood"
            :maxlength="10"
            @search="search"
            @cancel="cancel"
            @clear="clear"
            @change="queryFood"
          />
        </wd-col>
      </wd-row>
      <wd-status-tip
        v-if="foodList == null || foodList.length === 0"
        type="search"
        tip="当前搜索无结果"
      />
      <view
        v-for="(item, index) in foodList"
        v-else
        :key="index"
        @click="detailPopup.handleDetailShow(item)"
      >
        <wd-card :title="item.name">
          <wd-row v-if="searchType === '饮食'" flex justify="space-between">
            <wd-col :span="14">
              <view style="color: #82d44f; font-weight: bold">{{ item.energyKcal }}千卡</view>
              <view>每100克</view>
            </wd-col>
            <wd-col :span="10">
              <view>蛋白质{{ item.protein }}克</view>
              <view>脂肪{{ item.fat }}克</view>
              <view>碳水化合物{{ item.carbohydrate }}克</view>
            </wd-col>
          </wd-row>
        </wd-card>
      </view>
    </view>
  </wd-popup>
  <FoodSportDetailPopup ref="detailPopup" :searchType="searchType" @weekCalendar="weekCalendar" />
  <view class="floating-button" @click="handleClick">
    <text>+</text>
  </view>
  <PlanSelect ref="planSelect" :increment="100" :title="'能量限额'" @get-plan="getEnergyPlan" />
</template>

<script setup lang="js">
import FoodInfoAPI from "@/api/food/food-info";
import moment from "moment";
import getWeekDays from "@/utils/weekTimeUtil";
import DietPlanAPI from "@/api/diet/diet-plan";
import UserEnergyPlanAPI from "@/api/energyPlan/user-energy-plan";
import PlanSelect from "@/components/my-component/planSelect.vue";
import DateProgress from "@/components/my-component/dateProgress.vue";
import FoodSportDetailPopup from "@/components/my-component/foodSportDetailPopup.vue";
import WeatherAPI from "@/api/system/weather";
import UserAPI from "@/api/system/user";
import { getToken } from "@/utils/cache";
const planSelect = ref();
const indexLoading = ref(false);
const showPanel = ref(false);
const searchType = ref("饮食");
const searchFood = ref();
const foodList = ref([]);
const datePlan = ref(moment(new Date()).format("YYYY-MM-DD"));
const dietPlan = ref([]);
const energyPlan = ref(0);
const dateProgress = ref();
const detailPopup = ref();
const weather = ref({
  obsTime: "",
  temp: "",
  feelsLike: "",
  icon: "",
  text: "",
  wind360: "",
  windDir: "",
  windScale: "",
  windSpeed: "",
  humidity: "",
  precip: "",
  pressure: "",
  vis: "",
  cloud: "",
  dew: ""
});
const city = ref({
  name: "",
  id: "",
  lat: "",
  lon: "",
  adm2: "",
  adm1: "",
  country: "",
  tz: "",
  utcOffset: "",
  isDst: "",
  type: "",
  rank: "",
  fxLink: ""
});
const hour = ref([
  {
    fxTime: "",
    temp: "",
    icon: "",
    text: "",
    wind360: "",
    windDir: "",
    windScale: "",
    windSpeed: "",
    humidity: "",
    pop: "",
    precip: "",
    pressure: "",
    cloud: "",
    dew: ""
  },
  {
    fxTime: "",
    temp: "",
    icon: "",
    text: "",
    wind360: "",
    windDir: "",
    windScale: "",
    windSpeed: "",
    humidity: "",
    pop: "",
    precip: "",
    pressure: "",
    cloud: "",
    dew: ""
  },
  {
    fxTime: "",
    temp: "",
    icon: "",
    text: "",
    wind360: "",
    windDir: "",
    windScale: "",
    windSpeed: "",
    humidity: "",
    pop: "",
    precip: "",
    pressure: "",
    cloud: "",
    dew: ""
  },
  {
    fxTime: "",
    temp: "",
    icon: "",
    text: "",
    wind360: "",
    windDir: "",
    windScale: "",
    windSpeed: "",
    humidity: "",
    pop: "",
    precip: "",
    pressure: "",
    cloud: "",
    dew: ""
  },
  {
    fxTime: "",
    temp: "",
    icon: "",
    text: "",
    wind360: "",
    windDir: "",
    windScale: "",
    windSpeed: "",
    humidity: "",
    pop: "",
    precip: "",
    pressure: "",
    cloud: "",
    dew: ""
  }
]);
const day = ref({
  fxDate: "",
  sunrise: "",
  sunset: "",
  moonrise: "",
  moonset: "",
  moonPhase: "",
  moonPhaseIcon: "",
  tempMax: "",
  tempMin: "",
  iconDay: "",
  textDay: "",
  iconNight: "",
  textNight: "",
  wind360Day: "",
  windDirDay: "",
  windScaleDay: "",
  windSpeedDay: "",
  wind360Night: "",
  windDirNight: "",
  windScaleNight: "",
  windSpeedNight: "",
  humidity: "",
  precip: "",
  pressure: "",
  vis: "",
  cloud: "",
  uvIndex: ""
});
const aqiLevel = ref("");
const carbo = ref({
  quantity: 0,
  percentage: 0,
});
const protein = ref({
  quantity: 0,
  percentage: 0,
});
const fat = ref({
  quantity: 0,
  percentage: 0,
});
const energy = ref(0);
const minus = ref(0);
onShow(async () => {
  const userInfo=await UserAPI.getProfile()
  if(userInfo.height&&userInfo.weight&&userInfo.age&&userInfo.gender){
    getEnergyPlan();
    handleDatePlanConfirm({ value: new Date() });
    weekCalendar(0);
  }else {
    uni.navigateTo({
      url: "/pages/mine/profile/index"
    })
  }
});
onMounted(()=>{
  let token=getToken()
  if (token){
    wx.getFuzzyLocation({
      type: "wgs84",
      success(res) {
        const latitude = res.latitude.toFixed(2);
        const longitude = res.longitude.toFixed(2);
        WeatherAPI.getWeather({ longitude, latitude }).then((res) => {
          res=JSON.parse(res)
          weather.value = res.weather;
          city.value = res.city;
          hour.value = res.hour;
          day.value = res.day;
          aqiLevel.value = res.aqiLevel;
        });
      },
    });
  }
})
function toTips(){
  uni.navigateTo({url:'/pages/index/tips'})
}
function weekCalendar(data) {
  minus.value += data;
  let date = new Date(datePlan.value);
  date.setDate(date.getDate() + 7 * data);
  let dates = getWeekDays(date);
  DietPlanAPI.weekCalendar(dates).then((res) => {
    if (res != null) {
      res.forEach((item) => {
        if (formatDate(date) === item.oriDate) {
          item.isSelected = true;
        }
      });
      dateProgress.value.showData(res);
      handleDatePlanConfirm({ value: new Date(date) });
    }
  }).catch((err) => {});;
}
function getEnergyPlan() {
  UserEnergyPlanAPI.getFormData().then((data) => {
    if (data != null) {
      energyPlan.value = data.energy;
    }
  }).catch((err) => {});
}
function handlePlanDel(id, type) {
  wx.showModal({
    title: "提示",
    content: "是否删除？",
    success(res) {
      if (res.confirm) {
        DietPlanAPI.deleteByIds(id).then((res) => {
          uni.showToast({ title: "删除成功", icon: "none" });
          weekCalendar(0)
        });
      }
    },
  });
}
function handleDatePlanConfirm({ value }) {
  indexLoading.value = true;
  datePlan.value = formatDate(new Date(value));
  DietPlanAPI.getPage({ planDate: datePlan.value, pageSize: 999 })
    .then((res) => {
      dietPlan.value = res.list;
      let carboRes = 0;
      let proteinRes = 0;
      let fatRes = 0;
      let quantityRes = 0;
      let energyRes = 0;
      res.list.forEach((item) => {
        let multiple = item.quantity / 100;
        carboRes += item.carbohydrate * multiple;
        proteinRes += item.protein * multiple;
        fatRes += item.fat * multiple;
        quantityRes = item.quantity;
        energyRes += item.energy;
      });
      if (quantityRes > 0) {
        let carboPercent = (carboRes / quantityRes) * 100;
        let proteinPercent = (proteinRes / quantityRes) * 100;
        let fatPercent = (fatRes / quantityRes) * 100;
        carbo.value.percentage = carboPercent.toFixed(1);
        protein.value.percentage = proteinPercent.toFixed(1);
        fat.value.percentage = fatPercent.toFixed(1);
      }else {
        carbo.value.percentage = 0;
        protein.value.percentage = 0;
        fat.value.percentage = 0;
      }
      carbo.value.quantity = carboRes.toFixed(1);
      protein.value.quantity = proteinRes.toFixed(1);
      fat.value.quantity = fatRes.toFixed(1);
      energy.value = energyRes.toFixed(1);
    }).catch((err) => {})
    .finally(() => {
      indexLoading.value = false;
    });
}
function formatDate(date) {
  let momentDate = moment(date);
  return momentDate.format("YYYY-MM-DD");
}
function cancel() {
  showPanel.value = false;
  handleDatePlanConfirm({ value: new Date() });
  clear();
}
function clear() {
  searchFood.value = "";
  foodList.value = [];
}
function queryFood() {
  console.log(searchFood.value);
}
function search() {
  if (searchFood.value != null && searchFood.value !== "") {
    FoodInfoAPI.getPage({ name: searchFood.value, pageSize: 999 }).then((res) => {
      foodList.value = res.list;
    });
    console.log(searchType.value);
  } else {
    foodList.value = [];
  }
}
function handleClick(e) {
  showPanel.value = !showPanel.value;
}
</script>

<style setup lang="scss">
.custom-txt {
  color: black;
  width: 400rpx;
  height: 400rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 40rpx;
  border-radius: 32rpx;
}
.detailHead {
  display: flex;
  align-items: center;
  padding: 10px;
}
.sportCard {
  height: 70px;
  display: flex;
  align-items: center;
}
.scroll-view_H {
  white-space: nowrap;
  width: 100%;
  padding: 10px 20px 5px 20px;
}
.scroll-view-item_H {
  display: inline-block;
  width: 90vw;
  white-space: nowrap;
  text-align: center;
  font-size: 36rpx;
  padding: 10px;
}
.foodCard {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.carbon {
  font-size: 12px;
  color: #0079fe;
  margin-right: 10px;
  width: 30%;
  text-align: left;
}
.protein {
  font-size: 12px;
  color: #33c759;
  margin-right: 10px;
  width: 30%;
  text-align: left;
}
.fat {
  font-size: 12px;
  color: #fe9400;
  margin-right: 10px;
  width: 30%;
  text-align: left;
}
.process {
  width: 60%;
  font-size: 10px;
}
.foodPlanTitle {
  color: #82d44f;
  padding: 10px 20px 5px 40px;
}
.planContent {
  padding: 10px 20px 5px 20px;
}
.floating-button {
  position: fixed;
  bottom: 150px;
  right: 20px;
  width: 60px;
  height: 60px;
  background-color: #82d44f;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #fff;
  font-size: 30px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
  z-index: 999; /* 确保按钮浮在最前 */
}
.flexSpaceBetween {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.sportTitle {
  font-size: 15px;
  font-weight: bold;
}
.sportContent {
  font-size: 12px;
}
</style>
